/**
 * @Title: SysLoginOutAction.java
 * @Package com.yly.system.login
 * @Description: TODO
 * @author zz
 * @date 2013-12-15 下午9:46:42
 * @version V1.0
 */
package com.yly.module.sys.security;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;
import com.yly.common.basic.action.BasicSupportAction;

/**
 * @ClassName: SysLoginOutAction
 * @Description: TODO
 * @author zz
 * @date 2013-12-15 下午9:46:42
 */
@SuppressWarnings("serial")
@Results(value = {
		@Result(name = ActionSupport.SUCCESS, location = "/url.jsp"),
		@Result(name = ActionSupport.INPUT, location = "/login.jsp"),
		@Result(name = "sys_main", location = "/WEB-INF/page/sys/basic_frame/main.jsp")})
public class SysLoginOutAction extends BasicSupportAction {

	protected static Log loger = LogFactory.getLog(SysLoginOutAction.class);

	@Action("login")
	public String login() {
		Subject currentUser = SecurityUtils.getSubject();
		String re = "sys_main";
		if (!currentUser.isAuthenticated()) {
			String userCode = this.getParam().get("user_code");
			String password = this.getParam().get("password");
			UsernamePasswordToken token = new UsernamePasswordToken(userCode,
					password);
			token.setRememberMe(true);
			boolean loginFlag = true;
			try {
				currentUser.login(token);
			} catch (UnknownAccountException uae) {
				loger.info("账户不存在!");
				loginFlag = false;
			} catch (IncorrectCredentialsException ice) {
				loger.info("密码不正确!");
				loginFlag = false;
			} catch (LockedAccountException lae) {
				loger.info("账户被禁了!");
				loginFlag = false;
			} catch (AuthenticationException ae) {
				loger.info("认证错误!");
				loginFlag = false;
			}
			
			if(loginFlag){
				loger.info("登陆成功!");
			}else{
				if(token != null){
					token.clear();
				}
				re = ActionSupport.INPUT;
			}
			
		}
		return re;
	}

	@Action("logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			subject.logout();
		}
		this.getRequest().getSession().invalidate();
		return ActionSupport.INPUT;
	};



}
